package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/joho/godotenv"
	//_ "github.com/joho/godotenv/autoload"
)

var (
	client *oss.Client
)

var (
	Endpoint        string = "xxx"
	AccessKeyId     string = "xxx"
	AccessKeySecret string = "xxx"
	MyBucket        string = ""
	UpFile          string = ""
)

func validate() error {
	if Endpoint == "" {

		return fmt.Errorf(" Endpoint is empty")
	}

	if AccessKeyId == "" || AccessKeySecret == "" {

		return fmt.Errorf(" Pelease check  AccessKeyId or  AccessKeySecret is  empty ")
	}
	if MyBucket == "" {
		return fmt.Errorf(" Pelease check  Bucket  is  empty ")
	}
	if UpFile == "" {

		return fmt.Errorf("Pelease check UpFile is empty ")
	}
	return nil

}
func ListBucket() {

	lsRes, err := client.ListBuckets()
	if err != nil {
		panic(err)
	}

	for _, bucket := range lsRes.Buckets {
		fmt.Println("Buckets:", bucket.Name)
	}

}

func UploadFile(UpFile string) error {

	bucket, err := client.Bucket(MyBucket)
	if err != nil {
		panic(err)
	}

	RemoteFile := UpFile
	err = bucket.PutObjectFromFile(RemoteFile, UpFile)
	if err != nil {
		panic(err)
	}
	fmt.Printf("文件上传成功，文件名是%s \n", UpFile)
	url, err := bucket.SignURL(UpFile, oss.HTTPGet, 60*60*24)
	if err != nil {
		panic(err)
	}
	fmt.Printf("文件下载url 是%s,  过期时间为1天\n", url)
	return nil
}

func DownloadFile() {

	bucket, err := client.Bucket(MyBucket)
	if err != nil {
		panic(err)
	}
	err = bucket.GetObjectToFile("2.sql", "3.sql")
	if err != nil {
		panic(err)
	}
}

func LoadParams() {
	flag.StringVar(&UpFile, "f", "", "指定文件")
	flag.Parse()

}

func init() {
	path, err := os.Getwd()
	if err != nil {
		fmt.Println(err)

	}
	env_path := path + "\\etc\\aliyun.env"
	fmt.Println(env_path)

	err = godotenv.Load(env_path)
	fmt.Println(err)
	Endpoint = os.Getenv("Endpoint")
	AccessKeyId = os.Getenv("AccessKeyId")
	AccessKeySecret := os.Getenv("AccessKeySecret")
	MyBucket = os.Getenv("MyBucket")

	//s3_MyBucket := os.Getenv("MyBucket")
	//fmt.Println(Endpoint, AccessKeyId, AccessKeySecret)

	c, err := oss.New(Endpoint, AccessKeyId, AccessKeySecret)
	if err != nil {
		panic(err)
	}
	fmt.Println("初始化成功")
	client = c
}

func main() {

	LoadParams()
	if err := validate(); err != nil {
		fmt.Printf("validate is error,error is %s", err)
		os.Exit(1)
	}
	if err := UploadFile(UpFile); err != nil {
		fmt.Printf("upload file failed ,error is %s", err)
		os.Exit(1)
	}

	//fmt.Printf(" 上传文件成功，文件名为 %s\n", UpFile)

}
